package com.lb.algorithm;

import java.util.Arrays;

/**
 * @version 1.0
 * @Author: Edward
 * @Date: 2021/10/20 10:30
 * @Description: 计算排序
 */
public class CountSort {

    public static void main(String[] args) {
        int[] arr = {2,4,2,3,7,1,1,0,0,5,6,9,8,5,7,4,0,9};

        System.out.println(Arrays.toString(arr));

        int[] result = sort(arr);

        System.out.println(Arrays.toString(result));
    }

    private static int[] sort(int[] arr) {
        int[] result = new int[arr.length];

        // 计数数组
        int[] count = new int[10];

        // 统计各数出现次数
        for (int i = 0; i < arr.length; i++) {
            count[arr[i]]++;
        }

        System.out.println(Arrays.toString(count));

        // 不稳定
//        for (int i = 0,j = 0; i < count.length; i++) {
//            while (count[i]-- > 0) {
//                result[j++] = i;
//            }
//        }

        // 稳定处理
        // 求count数组的累加数组，即获取每一个元素最后一个元素出现的位置
        for (int i = 1; i < count.length; i++) {
            count[i] = count[i] + count[i - 1];
        }
        System.out.println(Arrays.toString(count));

        for (int i = arr.length - 1; i >= 0; i--) {
            result[--count[arr[i]]] = arr[i];
        }

        return result;
    }

    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
